package com.situ.ui;

import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

/**
 * Created by Gao on 2021/11/26.
 */

public class FruitAdapter extends ArrayAdapter<Fruit>{
    private static final String TAG = "FruitAdapter";
    private int resourceId;

    /**
     *
     * @param context Activity上下文
     * @param resource  fruit_item布局
     * @param objects  List<Fruit>
     */
    public FruitAdapter(Context context, int resource, List<Fruit> objects) {
        super(context, resource, objects);
        resourceId = resource;
    }

    // Fruit-> fruit_item
    // 数据到布局的绑定
    // position: 要渲染的位置从0
    // convertView: fruit_item布局
    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Log.d(TAG, "getView: position: " + position);
        Fruit fruit = getItem(position);
        ViewHolder viewHolder;

        /*viewHolder = new ViewHolder();
        convertView = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
        viewHolder.fruitImage = (ImageView) convertView.findViewById(R.id.fruit_image);
        viewHolder.fruitName = (TextView) convertView.findViewById(R.id.fruit_name);*/

        // 第一次渲染这个convertView是null
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
            viewHolder.fruitImage = (ImageView) convertView.findViewById(R.id.fruit_image);
            viewHolder.fruitName = (TextView) convertView.findViewById(R.id.fruit_name);
            // 将ViewHolder存贮到convertView上
            convertView.setTag(viewHolder);
        } else {// 之后就不需要重新获取，直接从getTag中获取
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.fruitImage.setImageResource(fruit.getImageId());
        viewHolder.fruitName.setText(fruit.getName());
        return  convertView;
    }

    // 封装fruit_item里面的控件
    class ViewHolder{
        ImageView fruitImage;
        TextView fruitName;
    }
}
